#! /bin/sh

source /etc/rc.d/common

SYSFS_RBD="/sys/bus/rbd"
RBDMAP_FILE="/etc/ceph/rbdmap"
CEPHCONF_FILE="/etc/ceph/ceph.conf"

check_args ${@}

start() {
    # Make sure the map file exists
    if [ ! -f "${RBDMAP_FILE}" ]; then
        /bin/echo "RBD Mapping: The ${RBDMAP_FILE} file is missing!"
        exit 1
    fi

    # Read the file and creating mapping(s)
    /bin/echo "Mapping all Ceph RBD images..."
    while read dev params; do
        case "${dev}" in
            ""|\#*)
                continue
                ;;
            */*)
                ;;
            *)
                dev=rbd/${dev}
                ;;
        esac

        if [ ! -b /dev/rbd/${dev} ]; then
            mons=$(/bin/egrep 'mon[ _]host' ${CEPHCONF_FILE} | \
                /usr/bin/cut -f2 -d'=' | /usr/bin/sed 's/ //g')
            name=$(/bin/echo ${params} | /bin/grep -o id=.*, | \
                /usr/bin/cut -d',' -f1 | /usr/bin/cut -d'=' -f2 | \
                /usr/bin/sed 's/id=/name=/g')
            keyring=$(/bin/echo ${params} | /bin/grep -o keyring.* | \
                /usr/bin/cut -d'=' -f2)
            secret=$(/bin/grep 'key =' ${keyring} | /usr/bin/cut -d' ' -f3)
            rbddev=$(/bin/echo ${dev} | /usr/bin/tr '/' ' ')
            /bin/echo "${mons} name=${name},secret=${secret} ${rbddev}" > \
                ${SYSFS_RBD}/add
        fi
    done < ${RBDMAP_FILE}
}

stop() {
    /bin/echo "Unmapping all Ceph RBD images..."
    cd ${SYSFS_RBD}/devices/
    if /bin/ls * > /dev/null 2>&1; then
        for dev in *; do
            /bin/echo ${dev} > ${SYSFS_RBD}/remove
        done
    fi
}

status() {
    # We don't know anything
    exit ${UNKNOWN}
}

# Perform specified action
${1}
